﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
// ReSharper disable LocalizableElement

namespace VeryGoodSync
{
    public partial class Form1 : Form
    {
        private readonly FileSystemWatcher _configWatcher;
        private readonly List<JobWorker> _workers = new List<JobWorker>();
        private int _animationRequestCount;
        private int _iconIndex;
        private readonly Icon[] _icons;
        private bool _realClose = false;
        private SetTimeout _restartTimer;
        private SetTimeout _stopAnimationTimer;
        private bool _isAnimationStopped = true;
        private string _currentIcon;


        public Form1()
        {
            if (!File.Exists("VeryGoodSync.xml"))
            {
                File.Create("VeryGoodSync.xml").Close();
            }

            _icons = new[]
            {
                Properties.Resources._1,
                Properties.Resources._2,
                Properties.Resources._3,
                Properties.Resources._4,
                Properties.Resources._5,
                Properties.Resources._6,
                Properties.Resources._7,
                Properties.Resources._8
            };

            InitializeComponent();
            Visible = false;
            ShowInTaskbar = false;
            WindowState = FormWindowState.Minimized;
            Ui.ShowNoticeRequest += UI_ShowNoticeRequest;
            Ui.ControlAnimationRequest += UI_ControlAnimationRequest;
            _configWatcher = new FileSystemWatcher(Directory.GetCurrentDirectory(), "VeryGoodSync.xml");
            _configWatcher.Changed += _configWatcher_Changed;
            _configWatcher.EnableRaisingEvents = true;
            Closed += Form1_Closed;
            Closing += Form1_Closing;
        }

        private async void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (_realClose) return;
            e.Cancel = true;
            WindowState = FormWindowState.Minimized;
            await Task.Delay(200);
            Visible = false;
            ShowInTaskbar = false;
        }

        private void UI_ControlAnimationRequest(bool show)
        {
            if (show)
            {
                Interlocked.Increment(ref _animationRequestCount);
            }
            else
            {
                Interlocked.Decrement(ref _animationRequestCount);
            }

            if (_animationRequestCount > 0)
            {
                _isAnimationStopped = false;
                return;
            }

            _stopAnimationTimer?.Cancel();
            _stopAnimationTimer = SetTimeout.New(1000, () => { _isAnimationStopped = true; });
        }

        private void _configWatcher_Changed(object sender, FileSystemEventArgs e)
        {
            _restartTimer?.Cancel();
            _restartTimer = SetTimeout.New(1000, ReStartJob);
        }

        private void Form1_Closed(object sender, EventArgs e)
        {
            notifyIcon1.Visible = false;
            _configWatcher.Dispose();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            ReStartJob();
        }

        void ReStartJob()
        {
            var config = VeryGood.LoadConfig();
            if (config == null)
            {
                Environment.Exit(0);
                return;
            }

            foreach (var worker in _workers)
            {
                worker.KnockOff();
            }

            foreach (var job in config.Jobs)
            {
                try
                {
                    _workers.Add(new JobWorker(job));
                }
                catch (Exception ex)
                {
                    Ui.ShowError(ex);
                }
            }
        }

        private void UI_ShowNoticeRequest(string title, string message, ToolTipIcon icon, int time)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() =>
                {
                    InfoWindow.Show(message);
                    notifyIcon1.Text = $"[{Text}]-{message}";
                    notifyIcon1.ShowBalloonTip(time, title, message, icon);
                }));
            }
            else
            {
                InfoWindow.Show(message);
                notifyIcon1.Text = $"[{Text}]-{message}";
                notifyIcon1.ShowBalloonTip(time, title, message, icon);
            }
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ShowInTaskbar = true;
            Visible = true;
            WindowState = FormWindowState.Normal;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (_isAnimationStopped)
            {
                if (_currentIcon == "sync_pyq" ||
                    _currentIcon == "_9") return;
                notifyIcon1.Icon = Properties.Resources.sync_pyq;
                _currentIcon = "sync_pyq";
            }
            else
            {
                notifyIcon1.Icon = _icons[_iconIndex];
                _iconIndex++;
                if (_iconIndex >= _icons.Length) _iconIndex = 0;
                _currentIcon = "";
            }
        }

        private void 退出程序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要退出程序么？退出后将不再提供同步功能！", "温馨提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) ==
                DialogResult.Yes)
            {
                Application.Exit();
            }
        }

        private void 配置文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var explorerDir = Environment.GetFolderPath(Environment.SpecialFolder.Windows);
            var explorer = Path.Combine(explorerDir, "explorer.exe");
            if (File.Exists(explorer))
                Process.Start(explorer, $"/select,{Path.Combine(Directory.GetCurrentDirectory(), "VeryGoodSync.xml")}");
        }

        private void 暂停同步ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!(sender is ToolStripMenuItem menuItem)) return;
            if (menuItem.Text == "暂停同步")
            {
                menuItem.Text = "恢复同步";
                _workers.ForEach(ele => ele.IsPaused = true);
                notifyIcon1.Icon = Properties.Resources._9;
                _currentIcon = "_9";
            }
            else
            {
                menuItem.Text = "暂停同步";
                _workers.ForEach(ele => ele.IsPaused = false);
                notifyIcon1.Icon = Properties.Resources.sync_pyq;
                _currentIcon = "sync_pyq";
            }
        }

        private void 全部同步ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (var worker in _workers.ToArray())
            {
                worker.DoSync();
            }
        }
    }
}
